package hibatis.support.parse;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by huangdachao on 2018/6/24 15:36.
 */
public class Table {
    /** 表名模式 */
    public static final Pattern TABLE_PATTERN = Pattern.compile("\\$\\(([a-zA-Z_][a-zA-Z0-9_]*(\\.[a-zA-Z_][a-zA-Z0-9_]*)?)\\)");

    public final String table;
    public final String alias;

    public Table(String table) {
        this.table = table;
        this.alias = "";
    }

    public Table(String table, String alias) {
        this.table = table;
        this.alias = alias;
    }

    public static Set<Table> parse(String placeholder, EntityMeta em) {
        Matcher matcher = TABLE_PATTERN.matcher(placeholder);
        Set<Table> list = new HashSet<>();
        while (matcher.find()) {
            String[] arr = matcher.group(1).split("\\.");
            list.add(new Table(arr[0], arr.length > 1 ? arr[1] : ""));
        }

        matcher = TableColumn.ENTITY_FIELD_TABLE_COLUMN_PATTERN.matcher(placeholder);
        while (matcher.find()) {
            String field = matcher.group(1);
            TableColumn tc = em.getFieldsMap().get(field);
            if (tc != null) {
                list.add(tc.toTable());
            }
        }
        return list;
    }

    @Override
    public String toString() {
        return "Table{" +
            "table='" + table + '\'' +
            ", alias='" + alias + '\'' +
            '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Table)) {
            return false;
        }
        Table table1 = (Table) o;
        return Objects.equals(table, table1.table) &&
            Objects.equals(alias, table1.alias);
    }

    @Override
    public int hashCode() {
        return Objects.hash(table, alias);
    }
}
